package team.fourth.combat.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import team.fourth.combat.dao.OrderSettingMapper;
import team.fourth.combat.pojo.OrderSetting;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingMapper orderSettingMapper;
    @Override
    public void setNumberByDate(OrderSetting orderSetting) {
        Date orderDate = orderSetting.getOrderDate();
        //根据日期查询是否存在预约设置
       Integer count =  orderSettingMapper.findCountByDate(orderDate);

        if(count > 0){
            //如果存在就更新
            orderSettingMapper.edit(orderSetting);
        } else {
            //不存在就插入
            orderSettingMapper.add(orderSetting);
        }


    }



    @Override
    public void batchSave(List<OrderSetting> orderSettings) {
//        for (OrderSetting orderSetting : orderSettings) {
////            setNumberByDate(orderSetting);
////        }

        //把orderSettings拆分
        List<List<OrderSetting>> partition = Lists.partition(orderSettings, 50);

        //使用多线程导入
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        long start = System.currentTimeMillis();
        for (List<OrderSetting> settings : partition) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    for (OrderSetting setting : settings) {
                        setNumberByDate(setting);
                    }
                }
            });
        }

        long end = System.currentTimeMillis();

        System.out.println(end - start);

    }

    @Override
    public List<OrderSetting> getOrderSettingByMonth(String date) {//2020-01
        String start = date + "-01";
        String end = date + "-31";
        List<Map> result = new ArrayList<>();

        List<OrderSetting> orderSettings = orderSettingMapper.getOrderSettingByMonth(start,end);
        //{"date":22,"mouth":0,"number":300,"reservations":300,}
//        if(CollectionUtil.isNotEmpty(orderSettings)){
//            for (OrderSetting orderSetting : orderSettings) {
//                Map map = new HashMap();
//                Date orderDate = orderSetting.getOrderDate();
//                map.put("date",orderDate.getDate());
//                map.put("mouth",orderDate.getMonth());
//                map.put("number",orderSetting.getNumber());
//                map.put("reservations",orderSetting.getReservations());
//                result.add(map);
//            }
//        }
        return orderSettings;

    }
}
